<?php
namespace Logic\System;
use Spartan\Lib\Logic;
use Spartan\Lib\Sender;

class Queue extends Logic{
	/**
	 * * 添加一个队列。。
	 * 可单独调用，也可被他人调用。
	 * @param bool|true $isSend
	 * @return array
	 */
    public function addQueue($isSend = true){
	    $arrData['type'] = strtoupper($this->getData('send_type',''));//发送的类型
	    if (!in_array($arrData['type'],['MOBILE','EMAIL'])){//如果没有传入，就用默认的。
		    return Array('发送类型只能为“MOBILE”，“EMAIL”。',0);
	    }
	    $arrData['send_to'] = $this->getData('send_to','');//发送的对像
	    if ($arrData['type']=='MOBILE'){
		    if (!isMobile($arrData['send_to'])){
			    return Array('验证类型为手机，却不是手机。',0);
		    }
	    }elseif ($arrData['type']=='EMAIL'){
		    if (!isEmail($arrData['send_to'])){
			    return Array('验证类型为邮箱，却不是邮箱。',0);
		    }
	    }
	    $strContent = $this->getData('content','');
	    $strTitle = $this->getData('title','');
	    if (!$strContent && !$strTitle){//如果没有内容，就要用模版的KEY查找。
			$objTpl = Tpl::instance($this->getData());
			$objTpl->setData($this->getData());
			$arrTpl = $objTpl->getTpl();
			if ($arrTpl[1] != 1 || !isset($arrTpl[2])){//对应的tpl_key没有模版
				return $arrTpl;
			}
		    $strTitle = $arrTpl[2]['title'];
		    $strContent = $arrTpl[2][strtolower($arrData['type']).'_info'];
	    }
	    $arrVarValue = $this->getData('value');//变量表
	    $arrVarValue && $arrVarValue = json_decode($arrVarValue,true);
	    $this->getData('rad_code') && $arrVarValue['rad_code'] = $this->getData('rad_code');
	    $arrVarValue['verify_id'] = max(0,$this->getData('verify_id'));
	    $arrData['content'] = $this->valid()->parseContent($strContent,$arrVarValue);
	    $arrData['title'] =  $this->valid()->parseContent($strTitle,$arrVarValue);
	    $arrData['add_time'] = date('Y-m-d H:i:s',time());
	    $arrData['type'] = $arrData['type']=='MOBILE'?2:1;//1邮件，2手机
	    $result = $this->Db()->insert('system_queue',$arrData);
        if($isSend == true && max(0,$result) > 0){
            $this->setData(['queue_id'=>$result])->sendQueue();
        }
        $arrData['queue_id'] = $result;
	    $arrData['type'] = $arrData['type']==2?'MOBILE':'EMAIL';//1邮件，2手机
	    return Array('success',1,$arrData);
    }

	/**
	 * 添加一个验证码队列
	 */
	public function addVerify(){
		$arrResult = $this->checkSendCondition();
		if ($arrResult[1] != 1){//不允许发送
			return $arrResult;
		}
		$arrTpl = Tpl::instance($this->getData())->getTpl();
		if ($arrTpl[1] != 1){//对应的tpl_key没有模版
			return $arrTpl;
		}
		$arrTpl = $arrTpl[2];//得到模版的记录集
		$this->Db()->startTrans('Create.addVerifyQueue');//开始事务

		$arrVerify = Verify::instance($this->getData())->add();
		if ($arrVerify[1] != 1 || !isset($arrVerify[2]) || !$arrVerify[2]){//添加验应码失败，没有队列
			$this->Db()->rollback();
			return $arrVerify;
		}
		$arrVerify = $arrVerify[2];//得到验证码的变量集
		//把读取到的模版加入getData，一会加入队列不用重新读取
		$this->setData(
			Array(
				'rad_code'=>$arrVerify['rad_code'],//生成的验证码
				'verify_id'=>$arrVerify['id'],
				'title'=>$arrTpl['title'],
				'content'=>$arrTpl[strtolower($arrVerify['type']).'_info'],
			)
		);
		$arrResult = $this->addQueue(false);//加入队列动作
		if ($arrResult[1] != 1 || !isset($arrResult[2]) || !$arrResult[2]){
			$this->Db()->rollback();
			return $arrResult;
		}
		$this->Db()->commit('Create.addVerifyQueue');
		if($this->getData('is_send') == true){
            $this->setData(['queue_id'=>$arrResult[2]['queue_id']])->sendQueue();
		}
		return Array('发送成功，请注意查收。',1,['rad_code'=>$arrVerify['rad_code']]);
	}

	/**
	 * 在发送某些模版时，需要对发送对像进行相关操作
	 * @return array
	 */
	public function checkSendCondition(){
		return Array('未在需要判断的发送模块。',1);

	}

    /*发送指定的队列*/
    public function sendQueue(){
        $options = Array(
            'limit'=>max(1,$this->getData('num',1)),//发送条数
            'where'=>Array(),
        );
        //指定队列ID，
        $strQueueId = $this->getData('queue_id','');
        if (is_numeric($strQueueId) && intval($strQueueId) > 0){
            $options['where']['id'] = $strQueueId;
        }elseif(stripos($strQueueId,',') > 0 && is_numeric(str_replace(',','',$strQueueId))){
            $options['where']['id'] = Array('IN',$strQueueId);
        }
        //如果指定发送标题
        $this->getData('title','') && $options['where']['title'] = $this->getData('title','');
        //如果指定发送接收者
        $this->getData('send_to','') && $options['where']['send_to'] = $this->getData('send_to','');
        //如果指定发送状态
        $this->getData('status','') && $options['where']['status'] = $this->getData('status');
        //发送某种类型
        $this->getData('type','') && $options['where']['type'] = $this->getData('type');
        //指定发送某一时间段的开始时间
        //指定发送某一时间段的开始时间  指定发送某一时间段的结束时间
        if (strtotime($this->getData('begin_time','')) && strtotime($this->getData('end_time',''))){
            $options['where']['add_time'] = Array(
                'between',
                $this->getData('begin_time',''),
                $this->getData('end_time','')
            );
        }
        if (!$options['where']){
            return Array('没有指定任何发送条件。',0);
        }
        $arrInfo = $this->Db()->select('system_queue',$options);
        !$arrInfo && $arrInfo = [];
        $arrSuccess = [0,0];//成功，失败
        $clsSender = Sender::instance();
        foreach($arrInfo as $v){
            $arrData = Array(
                'send_time' => date('Y-m-d H:i:s',time()),
            );
            if ($v['type'] == 2){//2='MOBILE'
                $arrResult = $clsSender->sms()
                    ->setMobile($v['send_to'])
                    ->setBody($v['content'])
                    ->send();
                if ($arrResult[1] != 1){
                    $arrData['send_info'] = $arrResult[0];
                    $arrData['status'] = 3;
                    $arrSuccess[1]++;
                }else{
                    $arrResult = $clsSender->getResult();
                    if (isset($arrResult[$v['send_to']]) && $arrResult[$v['send_to']][1] == 1){
                        $arrData['send_info'] = isset($arrResult[$v['send_to']][0])?$arrResult[$v['send_to']][0]:'success';
                        $arrData['status'] = 2;//成功
                        $arrSuccess[0]++;
                    }else{
                        $arrData['send_info'] = isset($arrResult[$v['send_to']][0])?$arrResult[$v['send_to']][0]:'未知错误';
                        $arrData['status'] = 3;//失败
                        $arrSuccess[1]++;
                    }
                }
            }elseif ($v['type'] == 1){//1='EMAIL'
                $arrResult = $clsSender->email()
                    ->setEmail($v['send_to'])
                    ->setMailInfo($v['title'],$v['content'])
                    ->send();
                if ($arrResult[1] != 1){
                    $arrData['send_info'] = $clsSender->getErrors();
                    $arrData['status'] = 3;
                    $arrSuccess[1]++;
                }else{
                    $arrData['send_info'] = isset($arrResult[0])?$arrResult[0]:'';
                    $arrData['status'] = 2;//成功
                    $arrSuccess[0]++;
                }
            }else{
                continue;
            }
            $options = Array(
                'where'=>Array('id'=>$v['id']),
            );
            $this->Db()->update('system_queue',$arrData,$options);
        }
        return Array('共发送'.count($arrInfo).'条，成功'.$arrSuccess[0].'条，失败'.$arrSuccess[1].'条。',1,$this->Db()->getLastSql());
    }

} 